<template>
  <view class="container">
    <!-- 导航栏 -->

    <!-- 表单 -->
    <view class="form-container">
      <!-- 宠物选择 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">选择宠物<text class="required">*</text></text>
          <picker 
            :value="petIndex" 
            :range="pets" 
            range-key="name"
            @change="onPetChange"
            class="picker"
          >
            <view class="picker-text">
              {{ selectedPet ? selectedPet.name : '请选择宠物' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 记录信息 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">类型<text class="required">*</text></text>
          <picker 
            :value="typeIndex" 
            :range="recordTypeLabels" 
            @change="onTypeChange"
            class="picker"
          >
            <view class="picker-text">
              {{ formData.type || '请选择类型' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">标题<text class="required">*</text></text>
          <textarea 
            v-model="formData.title" 
            placeholder="请输入标题" 
            class="textarea title-textarea"
            maxlength="100"
          />
        </view>



        <view class="form-item">
          <text class="label">提醒日期<text class="required">*</text></text>
          <picker 
            mode="date" 
            :value="formData.displayReminderTime" 
            @change="onReminderDateChange"
            class="picker"
          >
            <view class="picker-text">
              {{ formData.displayReminderTime || '请选择提醒日期' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">重复类型</text>
          <picker 
            :value="repeatIndex" 
            :range="repeatTypeLabels" 
            @change="onRepeatChange"
            class="picker"
          >
            <view class="picker-text">
              {{ selectedRepeatType || '不重复' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">是否启用</text>
          <switch 
            :checked="formData.isEnabled" 
            @change="onEnabledChange"
            color="#007AFF"
          />
        </view>





        <view class="form-item">
          <text class="label">备注</text>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            class="textarea"
            maxlength="200"
          />
        </view>
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-save-section">
      <button class="save-btn" @click="saveRecord">保存</button>
    </view>
  </view>
</template>

<script>
import { getPetList } from '@/api/pet.js'
import { getUserId, checkAndRedirectToLogin } from '@/utils/auth.js'
import { addreminder } from '@/api/reminder.js'
import { updateHealthReminder } from '@/api/reminder.js'
import { getDictData } from '@/api/dict.js'

export default {
  data() {
    return {
      pets: [],
      selectedPet: null,
      petIndex: -1,
      preSelectedPetId: null,
      healthRecordId: null, // 保存健康记录ID
      pendingType: null, // 保存待处理的类型参数
      pendingRepeatType: null, // 保存待处理的重复类型参数
      formData: {
        petId: '',
        type: '',
        title: '',
        reminderTime: new Date().toISOString().split('T')[0] + ' 00:00:00', // 默认今天日期，包含时间部分
        displayReminderTime: new Date().toISOString().split('T')[0], // 用于显示的日期格式（年月日）
        repeatType: '', // 重复类型，从字典获取默认值
        isEnabled: true, // 是否启用，默认为启用状态

        status: '0', // 默认为待处理状态
        remark: ''
      },

      repeatTypes: [], // 重复类型字典数据
      repeatTypeLabels: [], // 重复类型标签数组
      repeatIndex: 0, // 默认选择第一个

      recordTypes: [],
      recordTypeLabels: [],
      statusOptions: [],
      typeIndex: -1,
      statusIndex: 0 // 默认选择待处理状态
    }
  },
  async onLoad(options) {

    
    // 检查认证状态
    const token = uni.getStorageSync('token')
    const userId = uni.getStorageSync('userId')
    
    if (!token || !userId) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
      return
    }
    
    // 保存传入的petId参数
    if (options.petId) {
      this.preSelectedPetId = options.petId
    } else {
      
    }
    
    // 保存传入的健康记录ID参数
    if (options.healthRecordId) {
      this.healthRecordId = options.healthRecordId
    }
    
    // 保存传递过来的类型参数，等字典加载完成后再处理
    if (options.recordType || options.type) {
      this.pendingType = decodeURIComponent(options.recordType || options.type || '')
    }
    
    if (options.content || options.title) {
      this.formData.title = decodeURIComponent(options.content || options.title || '')
    }
    

    
    if (options.reminderTime || options.nextRemindTime) {
      let reminderTime = decodeURIComponent(options.reminderTime || options.nextRemindTime || '')
      // 如果传入的日期只包含日期部分（yyyy-MM-dd），则添加时间部分
      if (reminderTime && reminderTime.length === 10) { // yyyy-MM-dd格式长度为10
        reminderTime += ' 00:00:00'
      }
      this.formData.reminderTime = reminderTime
      // 设置显示用的日期（只包含年月日部分）
      this.formData.displayReminderTime = reminderTime.substring(0, 10)
    }
    
    if (options.status) {
      // 忽略传入的状态参数，始终保持默认的待处理状态
      this.formData.status = '0'
      this.statusIndex = 0
    }
    
    if (options.remark) {
      this.formData.remark = decodeURIComponent(options.remark || '')
    }
    
    if (options.repeatType) {
      const repeatType = decodeURIComponent(options.repeatType || '')
      // 延迟处理repeatType参数，等字典数据加载完成后再处理
      this.pendingRepeatType = repeatType
    }
    

    
    this.loadPets()
    // 确保字典数据加载完成后再继续
    await this.loadDictData()
    
    // 字典加载完成后处理待处理的类型参数
    if (this.pendingType) {
      this.formData.type = this.pendingType
      // 设置对应的索引
      const typeIndex = this.recordTypeLabels.indexOf(this.pendingType)
      if (typeIndex !== -1) {
        this.typeIndex = typeIndex
      }
      this.pendingType = null
    }
    
    // 字典加载完成后处理待处理的重复类型参数
    if (this.pendingRepeatType) {
      // 查找匹配的字典值
      const repeatTypeIndex = this.repeatTypes.findIndex(item => item.dictValue === this.pendingRepeatType)
      if (repeatTypeIndex !== -1) {
        this.repeatIndex = repeatTypeIndex
        this.formData.repeatType = this.repeatTypes[repeatTypeIndex].dictValue
      } else {
        // 如果没有找到匹配的字典值，尝试匹配标签
        const labelIndex = this.repeatTypeLabels.indexOf(this.pendingRepeatType)
        if (labelIndex !== -1) {
          this.repeatIndex = labelIndex
          this.formData.repeatType = this.repeatTypes[labelIndex].dictValue
        } else {
          // 如果都没有找到，使用默认值
          this.repeatIndex = 0
          this.formData.repeatType = this.repeatTypes[0]?.dictValue || ''
        }
      }
      this.pendingRepeatType = null
    }
  },
  computed: {
    selectedRepeatType() {
      return this.repeatTypeLabels[this.repeatIndex] || '不重复'
    }
  },
  mounted() {
    console.log('debug - mounted - recordTypeLabels:', this.recordTypeLabels)
    console.log('debug - mounted - typeIndex:', this.typeIndex)
    console.log('debug - mounted - formData.type:', this.formData.type)
  },
  methods: {
    async loadPets() {
      try {
        // 使用统一的认证检查函数
        if (!checkAndRedirectToLogin('请先登录')) {
          return
        }
        
        const userId = getUserId()
        const response = await getPetList(userId)
        
        if (response && response.code === 200) {
          const petData = response.rows || response.data || []
          this.pets = petData
          
          // 如果有预选的petId，自动选中对应的宠物
          if (this.preSelectedPetId) {
            
            const petIndex = this.pets.findIndex(pet => {
              // 尝试多种匹配方式
              const match1 = pet.id == this.preSelectedPetId // 宽松匹配
              const match2 = pet.id === this.preSelectedPetId // 严格匹配
              const match3 = String(pet.id) === String(this.preSelectedPetId) // 字符串匹配
      
              return match1 || match2 || match3
            })
            
      
            if (petIndex !== -1) {
              this.petIndex = petIndex
              this.selectedPet = this.pets[petIndex]
              this.formData.petId = this.selectedPet.id
        
            } else {

            }
          }
        } else {
          this.pets = []
          uni.showToast({
            title: response?.msg || '加载宠物列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
    
        this.pets = []
        uni.showToast({
          title: '加载宠物列表失败',
          icon: 'none'
        })
      }
    },
    
    onPetChange(e) {
      this.petIndex = e.detail.value
      this.selectedPet = this.pets[this.petIndex]
      this.formData.petId = this.selectedPet.id
    },
    
    onTypeChange(e) {
      console.log('debug - type change event:', e.detail.value)
      console.log('debug - recordTypeLabels:', this.recordTypeLabels)
      this.typeIndex = e.detail.value
      this.formData.type = this.recordTypeLabels[e.detail.value]
      console.log('debug - selected type:', this.formData.type)
    },
    
    onReminderDateChange(e) {
      // 将日期格式转换为后端期望的 yyyy-MM-dd HH:mm:ss 格式
      const dateValue = e.detail.value
      if (dateValue) {
        this.formData.reminderTime = dateValue + ' 00:00:00'
        this.formData.displayReminderTime = dateValue // 用于显示的只包含年月日
      } else {
        this.formData.reminderTime = ''
        this.formData.displayReminderTime = ''
      }
    },

    onRepeatChange(e) {
      this.repeatIndex = e.detail.value
      // 存储重复类型的字典值，而不是索引或标签
      const selectedRepeatType = this.repeatTypes[this.repeatIndex]
      this.formData.repeatType = selectedRepeatType ? selectedRepeatType.dictValue : ''
    },

    onEnabledChange(e) {
      this.formData.isEnabled = e.detail.value
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    validateForm() {
      if (!this.formData.petId) {
        uni.showToast({
          title: '请选择宠物',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.type) {
        uni.showToast({
          title: '请选择提醒类型',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.title.trim()) {
        uni.showToast({
          title: '请输入提醒标题',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.reminderTime) {
        uni.showToast({
          title: '请选择提醒日期',
          icon: 'none'
        })
        return false
      }
      
      // 验证提醒时间不能小于当前时间
      if (this.formData.reminderTime) {
        const currentDate = new Date()
        const reminderDate = new Date(this.formData.reminderTime)
        
        // 重置时间为当天开始，只比较日期部分
        const currentDateOnly = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate())
        const reminderDateOnly = new Date(reminderDate.getFullYear(), reminderDate.getMonth(), reminderDate.getDate())
        

        
        if (reminderDateOnly < currentDateOnly) {
          uni.showToast({
            title: '提醒时间不能小于当前时间',
            icon: 'none'
          })
          return false
        }
        

      }
      
      return true
    },
    
    async saveRecord() {
      if (!this.validateForm()) {
        return
      }
      
      // 直接保存提醒
      this.saveReminder()
    },
    
    async saveReminder() {
      // 使用统一的认证检查函数
      if (!checkAndRedirectToLogin('请先登录')) {
        return
      }
      
      uni.showLoading({
        title: '保存中...'
      })
      
      try {

        
        // 准备提交数据
        const submitData = {
          petId: this.formData.petId,
          userId: getUserId(), // 添加用户ID
          reminderType: this.formData.type,
          title: this.formData.title,
          reminderTime: this.formData.reminderTime,
          repeatType: this.formData.repeatType, // 添加重复类型
          isEnabled: this.formData.isEnabled ? '1' : '0', // 添加是否启用字段
          status: this.formData.status,
          remark: this.formData.remark // 添加备注字段
        }
        
        // 使用提醒API添加记录
        const response = await addreminder(submitData)
        
        uni.hideLoading()
        
  
        
        // 检查响应数据
        if (response && response.code === 200) {
          // 如果有健康记录ID，更新健康记录的reminder_id
          if (this.healthRecordId) {
            try {
              const reminderId = response.reminderId // 从返回数据中获取reminderId
              await updateHealthReminder({ id: this.healthRecordId, reminderId: reminderId })
              
              // 发送事件通知健康记录页面刷新
              uni.$emit('healthrecordupdated')
            } catch (updateError) {
              console.error('更新健康记录reminder_id失败:', updateError)
              // 即使更新失败也不影响提醒保存的成功提示
            }
          }
          
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 发送事件通知列表页面刷新
          uni.$emit('reminderupdated')
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          // 业务逻辑错误
          const errorMsg = response?.msg || response?.message || '保存失败'
    
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
  
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },
    
    async loadDictData() {
    try {

      
      // 加载记录类型字典
      console.log('Debug - Loading pet_health_type dictionary...')
        const recordTypeResponse = await getDictData('pet_health_type')
      console.log('Debug - pet_health_type response:', recordTypeResponse)
      if (recordTypeResponse && recordTypeResponse.code === 200) {
        this.recordTypes = recordTypeResponse.data || []
        this.recordTypeLabels = this.recordTypes.map(item => item.dictLabel)
        console.log('Debug - Loaded recordTypes:', this.recordTypes)
        console.log('Debug - recordTypeLabels:', this.recordTypeLabels)
      } else {
        console.error('加载记录类型字典失败:', error)
        // 字典数据加载失败时，使用空数组，不提供硬编码默认值
        this.recordTypes = []
        this.recordTypeLabels = []
      }
      
      // 加载重复类型字典
      console.log('Debug - Loading repeat_type dictionary...')
      const repeatTypeResponse = await getDictData('repeat_type')
      console.log('Debug - repeat_type response:', repeatTypeResponse)
      if (repeatTypeResponse && repeatTypeResponse.code === 200) {
        this.repeatTypes = repeatTypeResponse.data || []
        this.repeatTypeLabels = this.repeatTypes.map(item => item.dictLabel)
        console.log('Debug - Loaded repeatTypes:', this.repeatTypes)
        console.log('Debug - repeatTypeLabels:', this.repeatTypeLabels)
        
        // 设置默认重复类型为第一个选项
        if (this.repeatTypes.length > 0 && !this.formData.repeatType) {
          this.formData.repeatType = this.repeatTypes[0].dictValue
        }
      } else {
        console.error('加载重复类型字典失败:', error)
        // 字典数据加载失败时，使用空数组，不提供硬编码默认值
        this.repeatTypes = []
        this.repeatTypeLabels = []
      }
      

      
      // 加载状态字典
      const statusResponse = await getDictData('pet_health_status')
      if (statusResponse && statusResponse.code === 200) {
        this.statusOptions = statusResponse.data || []
      } else {
        // 默认值
        this.statusOptions = [
          { dictLabel: '待处理', dictValue: 'pending' },
          { dictLabel: '已完成', dictValue: 'completed' },
          { dictLabel: '已逾期', dictValue: 'overdue' }
        ]
      }
      

      
      if (this.statusOptions.length > 0) {
        this.formData.status = '0' // 默认待处理状态
      }
      

      
    } catch (error) {
      // 使用默认值
      this.recordTypes = [
        { dictLabel: '疫苗', dictValue: '疫苗' },
        { dictLabel: '驱虫', dictValue: '驱虫' },
        { dictLabel: '体检', dictValue: '体检' },
        { dictLabel: '洗澡', dictValue: '洗澡' },
        { dictLabel: '喂药', dictValue: '喂药' },
        { dictLabel: '其他', dictValue: '其他' }
      ]
      this.recordTypeLabels = this.recordTypes.map(item => item.dictLabel)
      
      // 重复类型默认值
      this.repeatTypes = []
      this.repeatTypeLabels = []

      
      // 状态类型字典数据加载失败时，使用空数组，不提供硬编码默认值
      this.statusOptions = []
    }
  }
}
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.back-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.form-container {
  padding: 20rpx;
  flex-grow: 1; /* Allow form to grow and take available space */
  position: relative;
  z-index: 1;
}

/* 底部保存按钮区域 */
.bottom-save-section {
  padding: 20rpx;
  background: #fff;
  border-top: 1px solid #eee;
}

.save-btn {
  width: 100%;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.form-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  width: 180rpx;
  flex-shrink: 0;
  margin-right: 20rpx;
}

.required {
  color: #ff0000;
  margin-left: 4rpx;
  font-weight: bold;
}

.input, .picker, .textarea {
  flex: 1;
  min-height: 36rpx;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.picker-text {
  color: #333;
}

.textarea {
  height: 120rpx;
  resize: none;
}

.title-textarea {
  height: 120rpx; /* 记录标题使用较小的高度 */
  min-height: 36rpx;
  line-height: 1.4;
}

.input:focus, .textarea:focus {
  border-color: #007AFF;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
}

/* 是否启用开关样式 */
.form-item switch {
  flex-shrink: 0;
  margin-left: 20rpx;
}
</style>